package com.gouying.web.controller;

import com.alibaba.fastjson.JSON;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * 1:启动类添加@EnableCaching
 * 2: key 必须用''括起来
 */
@RestController
@AllArgsConstructor(onConstructor_ = @Autowired)
public class CacheController {



    @GetMapping("/addCache1")
    @Cacheable(value = {"test-cache"}, key = "'addCache1'", sync = true)
    public List<String> addCache1() {
        List<String> list = new ArrayList<>();
        list.add("1");
        list.add("2");
        list.add("3");
        return list;
    }


    @GetMapping("/addCache2")
    @Cacheable(value = {"test-cache"}, key = "'addCache2'", sync = true)
    public List<String> addCache2() {
        List<String> list = new ArrayList<>();
        list.add("4");
        list.add("5");
        list.add("6");
        return list;
    }

    @Caching(evict = {
            @CacheEvict(value = "test-cache", key = "'addCache1'"),
            @CacheEvict(value = "test-cache", key = "'addCache2'")
    })
    @GetMapping("/clearCache")
    public void clearCache() {

    }

    @NoArgsConstructor
    @AllArgsConstructor
    @Data
    private static class User{
        private Integer id;
        private String name;
    }


    @GetMapping("/find1")
    @Cacheable(value="users", key="#id")
    public String find1(Integer id) {
        return JSON.toJSONString(new User(id,"find1"));
    }
    @GetMapping("/find2")
    @Cacheable(value="users", key="#p0")
    public String find2(Integer id) {
        return JSON.toJSONString(new User(id,"find2"));
    }
    @PostMapping("/find3")
    @Cacheable(value="users", key="#user.id")
    public String find3(@RequestBody  User user) {
        user.setName("find3");
        return JSON.toJSONString(user);
    }
    @PostMapping("/find4")
    @Cacheable(value="users", key="#p0.id")
    public String find4(@RequestBody User user) {
        user.setName("find4");
        return JSON.toJSONString(user);
    }
    @GetMapping("/find5")
    @Cacheable(cacheNames="users", key="'mykey-'.concat(#root.methodName.concat('-').concat(#id))" )
    public String find5(Integer id) {
        return JSON.toJSONString(new User(id,"find5"));
    }


    @GetMapping("/clearFind")
    @Caching(evict = {
        @CacheEvict(value = "users" ,key = "'find1'"),
    })
    public String clearFind(Long id) {
        return "success";
    }

}
